//
//  SHOrdersNotificationViewController.swift
//  ServiceHelper
//
//  Created by Xuedan on 15/11/2.
//  Copyright © 2015年 Stan Wu. All rights reserved.
//

import UIKit

class SHOrdersNotificationViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,SHOrderDetailDelegate,UISearchBarDelegate,SHOrderNotificationDetailDelegate{
    var tvList: UITableView!
    var vDetail: SHOrderDetailView!
    var vNotificationDetail: SHOrdersNotificationDetailView!
    var aryList = NSMutableArray()
    var selectedOrder: NSDictionary?
    var refreshController: UIRefreshControl!
    var dCurrentPage = 1
    lazy var searchBar :UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 300,height: 20))
    var order_status: String = "1"
    var strNavTitle: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addBGColor()
        // Do any additional setup after loading the view.
//        self.addNavBack()
//        self.setNavTitle("预约处理")
//        self.navigationController?.navigationBarHidden = true
        self.setNavBGImage()
        searchBar.placeholder = "搜索"
        searchBar.delegate = self
        let rightNavBarButton = UIBarButtonItem(customView: searchBar)
        self.navigationItem.rightBarButtonItem = rightNavBarButton
        
        
        tvList = UITableView(frame: CGRect(x: 0, y: 0, width: 360, height: 768))
        tvList.backgroundColor = UIColor.clearColor()
        tvList.delegate = self
        tvList.dataSource = self
        tvList.separatorStyle = .None
        self.view.addSubview(tvList)
        
        vNotificationDetail = SHOrdersNotificationDetailView(frame: CGRect(x: 360, y: 0, width: 1024-360, height: 768))
        vNotificationDetail.backgroundColor = UIColor.whiteColor()
        vNotificationDetail.strNew = strNavTitle as NSString!
        vNotificationDetail.delegateNotification = self
        vNotificationDetail.strStatus = "2"
        self.view.addSubview(vNotificationDetail)
        
        vDetail = SHOrderDetailView(frame: CGRect(x: 360, y: 0, width: 1024-360, height: 768))
        vDetail.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.97, alpha: 1)
        vDetail.layer.shadowColor = UIColor.blackColor().CGColor
        vDetail.layer.shadowRadius = 1
        vDetail.layer.shadowOffset = CGSize(width: -2, height: 0)
        vDetail.layer.shadowOpacity = 0.1
        vDetail.delegate = self
        vDetail.hidden  = true
        self.view.addSubview(vDetail)
        
        NSThread.detachNewThreadSelector(#selector(SHOrdersNotificationViewController.loadData), toTarget: self, withObject: nil)
        
        refreshController = UIRefreshControl()
        refreshController.addTarget(self, action: #selector(SHOrdersNotificationViewController.refreshChanged(_:)), forControlEvents: .ValueChanged)
        tvList.addSubview(refreshController)
        
        
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh", name: "RefreshOrderList", object: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func refreshChanged(sender: UIRefreshControl){
        self.refresh()
    }
    
    func refresh(){
        NSThread.detachNewThreadSelector(#selector(SHOrdersNotificationViewController.loadData), toTarget: self, withObject: nil)
    }
    
    func loadData(){
        autoreleasepool { () -> () in
            dCurrentPage = 1;
            
            let dict = SHDataProvider.getDealerOrderList(["order_status":order_status,"dealer_id":SHDataProvider.getDealerID()])
            
            
            
            let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                if let orderList = ary{
                    self.aryList.removeAllObjects()
                    self.aryList = NSMutableArray(array: orderList)
                    
                    if orderList.count>0{
                        let formatter = NSDateFormatter()
                        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                        let d = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String)
                        if let dd = d{
                            NSUserDefaults.standardUserDefaults().setObject(dd, forKey: "LatestOrderTime")
                        }
                    }
                }else{
                    self.aryList.removeAllObjects()
                }
                
                self.tvList.reloadData()
                self.refreshController.endRefreshing()
                
                if self.aryList.count>0{
                    self.tableView(self.tvList, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
                }else{
                    self.vDetail.orderInfo = nil
                }
                
                
            })
        }
    }
    
    func loadMoreData(){
        autoreleasepool { () -> () in
            let dict = SHDataProvider.getDealerOrderList(["order_status": order_status,"dealer_id":SHDataProvider.getDealerID(),"page":"\(dCurrentPage+1)"])
            
            let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                if let orderList = ary{
                    self.aryList.removeAllObjects()
                    self.aryList.addObjectsFromArray(orderList)
                    self.dCurrentPage += 1
                }else{
                    
                }
                
                self.tvList.reloadData()
            })
        }
    }
    
    override func navBack() {
        self.dismissViewControllerAnimated(true, completion: nil)
//        self.dismiss(animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func statusChanged(sender: UISegmentedControl){
        if sender.selectedSegmentIndex==0{
            if !order_status.hasPrefix("1") {
                order_status = "1"
                refresh()
            }
        }else{
            if order_status.hasPrefix("1"){
                order_status = "2,3,4,5,6"
                refresh()
            }
        }
    }
    
    func showSelectedView(dic:NSDictionary?) {
        vNotificationDetail.hidden = true
        vDetail.hidden = false
    }
    
    
    // MARK: - UITableView Delegate & Data Source
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier = "OrderCell"
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell!
        
        if cell==nil{
            cell = UITableViewCell(style: .Default, reuseIdentifier: identifier)
            cell?.contentView.layer.borderWidth = 0.5
            cell?.contentView.layer.borderColor = UIColor(red: 0.82, green: 0.84, blue: 0.86, alpha: 1).CGColor
            cell?.contentView.backgroundColor = UIColor(red: 0.97, green: 0.98, blue: 0.99, alpha: 1)
            cell?.selectionStyle = .None
            
            var lbl: UILabel = UILabel.create(CGRect(x: 20, y: 15, width: 250, height: 19), font: UIFont.systemFontOfSize(18), textColor: UIColor.blackColor())
            lbl.tag = 100
            cell?.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRect(x: 20, y: 70, width: 250, height: 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 101
            cell?.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRect(x: 20, y: 95, width: 250, height: 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 102
            cell?.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRect(x: 20, y: 45, width: 250, height: 16), font: UIFont.systemFontOfSize(15), textColor: UIColor.grayColor())
            lbl.tag = 104
            cell?.contentView.addSubview(lbl)
            
            lbl = UILabel.create(CGRect(x: 308, y: 16, width: 33, height: 18), font: UIFont.systemFontOfSize(12), textColor: UIColor.whiteColor())
            lbl.tag = 103
            lbl.textAlignment = .Center
            cell?.contentView.addSubview(lbl)
            
            let line = UIView(frame: CGRect(x: 0, y: 124.5, width: 360, height: 0.5))
            line.backgroundColor = UIColor(white: 0.88, alpha: 1)
            cell?.contentView.addSubview(line)
            
            let circle = UIView(frame: CGRect(x: 0, y: 0, width: 8, height: 8))
            circle.clipsToBounds = true
            circle.layer.cornerRadius = 4
            circle.backgroundColor = UIColor.whiteColor()
            circle.tag = 200
            cell?.contentView.addSubview(circle)
            circle.center = CGPoint(x: 345, y: 62.5)
        }
        
        let lblName = cell?.contentView.viewWithTag(100) as! UILabel!
        let lblPhone = cell?.contentView.viewWithTag(101) as! UILabel!
        let lblOrderTime = cell?.contentView.viewWithTag(102) as! UILabel!
        let lblOrderType = cell?.contentView.viewWithTag(103) as! UILabel!
        let lblOrderNo = cell?.contentView.viewWithTag(104) as! UILabel!
        let circle = cell?.contentView.viewWithTag(200)!
        
        
        let orderInfo = aryList[indexPath.row]
        
        lblName?.text = orderInfo.objectForKey("nickname") as! String?
        lblOrderTime?.text = "预约时间：".stringByAppendingString(orderInfo.objectForKey("order_time") as! String!)
        
        if let orderType = orderInfo.objectForKey("order_type")?.intValue{
            lblOrderType?.hidden = false
            if 1==orderType{
                lblOrderType?.text = "保养"
                lblOrderType?.backgroundColor = UIColor(red: 0.02, green: 0.64, blue: 0.95, alpha: 1)
            }else{
                lblOrderType?.text = "维修"
                lblOrderType?.backgroundColor = UIColor(red: 0.95, green: 0.61, blue: 0.08, alpha: 1)
            }
        }else{
            lblOrderType?.hidden = true
        }
        
        if let checkNo = orderInfo.objectForKey("check_no") as! String!{
            lblOrderNo?.text = "预约单号：\(checkNo)"
        }else{
            lblOrderNo?.text = "预约单号：";
        }
        
        if let phone = orderInfo.objectForKey("order_phone") as! String!{
            lblPhone?.text = "联系电话：\(phone)"
        }else if let phone = orderInfo.objectForKey("phone") as! String!{
            lblPhone?.text = "联系电话：\(phone)"
        }else{
            lblPhone?.text = "联系电话："
        }
        
        
        if orderInfo as? NSObject == selectedOrder{
            cell?.contentView.backgroundColor = UIColor.lightGrayColor()
            lblOrderNo?.textColor = UIColor.whiteColor()
            lblPhone?.textColor = UIColor.whiteColor()
            lblOrderTime?.textColor = UIColor.whiteColor()
            lblName?.textColor = UIColor.whiteColor()
        }else{
            cell?.contentView.backgroundColor = UIColor.whiteColor()
            lblOrderNo?.textColor = UIColor.grayColor()
            lblPhone?.textColor = UIColor.grayColor()
            lblOrderTime?.textColor = UIColor.grayColor()
            lblName?.textColor = UIColor.blackColor()
        }
        
        circle?.hidden = false
        if let order_status = orderInfo.objectForKey("order_status")?.integerValue as Int!{
            if 1 == order_status{
                circle?.backgroundColor = UIColor(red: 0.99, green: 0.84, blue: 0.19, alpha: 1)
            }else if 2 == order_status{
                circle?.backgroundColor = UIColor.redColor()
            }else{
                circle?.backgroundColor = UIColor.greenColor()
            }
        }
        
        return cell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 125.0
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return aryList.count
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: 360, height: 120))
        v.backgroundColor = UIColor.whiteColor()
        
        let vNavTitleBG = UIView(frame: CGRect(x: 0, y: 0, width: 360, height: 50))
        vNavTitleBG.backgroundColor = UIColor(white: 0.94, alpha: 1)
        v.addSubview(vNavTitleBG)
        
        let lblNavTitle = UILabel(frame: CGRect(x: 0, y: 0, width: 360, height: 50))
        lblNavTitle.text = strNavTitle
        lblNavTitle.font = UIFont.systemFontOfSize(17)
        lblNavTitle.textAlignment = .Center
        lblNavTitle.textColor = UIColor(white: 0.30, alpha: 1)
        v.addSubview(lblNavTitle)
//        vNotificationDetail.str = strNavTitle
        
        let btnBack: UIButton = UIButton(frame: CGRect(x: 0, y: 15, width: 40, height: 20))
//        btnBack.clipsToBounds = true
//        btnBack.layer.cornerRadius = 4
//        btnBack.layer.borderWidth = 1
//        btnBack.layer.borderColor = UIColor(white: 1, alpha: 0.5).CGColor
        
        btnBack.setImage(UIImage(named: "back"), forState: UIControlState())
        btnBack.addTarget(self, action: #selector(UIViewController.navBack), forControlEvents: .TouchUpInside)
        v.addSubview(btnBack)
        
        
        let seg = UISegmentedControl(items: ["全部","新预约","支付通知"])
        seg.frame = CGRect(x: 20, y: 50 + 15, width: 320, height: 40)
        seg.center = CGPoint(x: 180, y: 50+35)
        seg.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)], forState: UIControlState())
        v.addSubview(seg)
        seg.addTarget(self, action: #selector(SHOrdersNotificationViewController.statusChanged(_:)), forControlEvents: .ValueChanged)
        
        if order_status.hasPrefix("1"){
            seg.selectedSegmentIndex = 0
        }else if order_status.hasPrefix("2"){
            seg.selectedSegmentIndex = 1
        }else{
            seg.selectedSegmentIndex = 2
        }
        
        return v
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section{
        case 0:
            return 120
        default:
            return 0.0
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let orderInfo: AnyObject = aryList[indexPath.row] as AnyObject
        vDetail.orderInfo = orderInfo as? NSDictionary
        selectedOrder = orderInfo as? NSDictionary
        
        tvList.reloadData()
    }
    
    //MARK: - MHOrderDetail Delegate
    func orderUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = (dict.objectForKey("order_id")! as AnyObject).intValue
            for i in 0 ..< aryList.count{
                let oi = ((aryList[i] as AnyObject).objectForKey("order_id") as AnyObject).intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    //MARK: - MHOrderDetailNotification Delegate
    func orderNotificationUpdated(order: NSDictionary?) {
        if let dict = order{
            let order_id = dict.objectForKey("order_id")?.intValue!
            for i in 0 ..< aryList.count{
                let oi = aryList[i].objectForKey("order_id")?.intValue!
                
                if order_id==oi{
                    aryList.replaceObjectAtIndex(i, withObject: dict)
                    break
                }
            }
            
            tvList.reloadData()
        }
    }
    
    
    
    // 输入框内容改变触发事件
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
            print("过滤：(searchText)")
    }
    // 书签按钮触发事件
    func searchBarBookmarkButtonClicked(searchBar: UISearchBar) {
            print("搜索历史")
    }

    // 取消按钮触发事件
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
            print("取消搜索")
    }

    // 搜索触发事件
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
            print("开始搜索")
    }

    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
